import axios from 'axios'
import BASE_URL from '@/config'
import { getToken } from '@/utils'
var qs = require('qs')

// 创建axios实例
const service = axios.create({
    headers: {
        // multipart/form-data
        'Content-Type': 'application/json;charset=UTF-8'
    },
    transformRequest: [function (data) {
        // Do whatever you want to transform the data
        // const request = qs.stringify({
        //   UToken: getToken('token'),
        //   data: data
        // })
        data.UToken = getToken('token')
        // data.UToken = '2i/yK9G+5yVOAgpMyNdmjjkMgL0arXedBkixEwwu+H02wCHJgTZsTxRjGC4nygWX'
        const request = JSON.stringify(data)
        return request
    }],
    baseURL: BASE_URL.BASE_API, // api的base_url
    timeout: 6000, // 请求超时时间
    responseType: 'json'
})

// request拦截器
service.interceptors.request.use(config => {
    config.headers['token'] = getToken('token') || ''
    return config
}, error => {
    // Do something with request error
    Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
    response => {
        // code为非200是抛错 可结合自己业务进行修改
        if (response.status >= 200 && response.status < 300) {
            return response.data
        } else {
            // eslint-disable-next-line prefer-promise-reject-errors
            return Promise.reject('error')
        }
    },
    error => {
        // 默认除了2XX之外的都是错误的，就会走这里
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    break
                default:
            }
        }
        return Promise.reject(error)
    }
)

export default service
